using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.SpriteKit;
using MonoTouch.UIKit;
using System.Collections.Generic;
using GameOfLifeX.Core;
using System.Threading.Tasks;

namespace GameOfLifeX.IOS
{
	public sealed class MyScene : SKScene
	{	
		private const int _cellCountHorizontal = 30;
		private const int _cellCountVertical = 60;
		private readonly float _cellWidth;
		private readonly float _cellHeight;
		private readonly BasicSprite[,] _cellSprites;

		private readonly Model _model;

		public MyScene (SizeF size) : base (size)
		{	
			BackgroundColor = new UIColor (0.15f, 0.15f, 0.3f, 1.0f);

			// Calculate cell dimensions
			_cellWidth = Frame.Width / _cellCountHorizontal;
			_cellHeight = Frame.Height / _cellCountVertical;
			var cellSize = new SizeF (_cellWidth, _cellHeight);

			// Instantiate sprite cells
			_cellSprites = new BasicSprite[_cellCountHorizontal, _cellCountVertical];
			for (int x = 0; x < _cellCountHorizontal; x++)
				for (int y = 0; y < _cellCountVertical; y++)
				{
					_cellSprites [x, y] = new BasicSprite (CalculateCellSpritePosition (x, y), cellSize);
					AddChild (_cellSprites [x, y]);
				}
		
			// Instantiate model
			_model = new Model (_cellCountHorizontal, _cellCountVertical);
			_model.SeedRandomly ();	
		}

		PointF CalculateCellSpritePosition (int x, int y)
		{
			var xPosition = x * _cellWidth;
			var yPosition = y * _cellHeight;
			return new PointF ((float)xPosition, (float)yPosition);
		}

		public override void Update (double currentTime)
		{
			_model.RunGeneration ();
			for(int x=0; x<_cellCountHorizontal; x++)
				for(int y=0; y<_cellCountVertical;y++)
				{
					_cellSprites[x,y].SetAlive (_model.GetGrid ()[x,y]);
					_cellSprites [x, y].StepFade ();
				}
					
			base.Update (currentTime);
		}
	}
}
